var mongoose = require('mongoose');
var util = require('util');

mongoose.connect('mongobd://127.0.0.1/test');


var schema1 = new mongoose.Schema({
	field1 : String,
	field2 : Number,
	list1 : [String],
	list2 : [{
		type : mongoose.Schema.ObjectId,
		ref : 's2'
	}]
});

var s1 = mongoose.model('s1', schema1);

var schema2 = new mongoose.Schema({
	field1 : String,
	field2 : Number,
	list1 : [String]
});

schema2.pre('save', function(next, done) {
	var self = this;
	
	s1.find(function(e, s) {
		s.forEach(function(ss) {
			ss.list2.push(self);
			ss.save(next);
		});
	});
});

var s2 = mongoose.model('s2', schema2);

var base = new s1();

base.field1 = 'Hello';
base.field2 = 42;
base.list1.push('Hi');
base.list1.push('There.');

base.save(function(e) {
	util.puts("Saving Base");
});

var a = new s2();
a.field1 = "asdf";
a.save(function(e) {
	util.puts("Saving Test");
	s1.find({}).populate('list2').run(function(e, s) {
		util.puts("Found " + s.length + " Entries");
		s.forEach(function(ss) {
			util.puts(util.inspect(ss));
		});
	});
});
